package club.justwill.single.persistence.store;

import club.justwill.single.impl.ToolsImpl;
import club.justwill.single.persistence.document.SessionData;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created by xiangnan on 16-1-14.
 */
@Component
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public class SessionDataStore extends MongoDbStore<SessionData> {
    public SessionData getByCookieId(String cookidId) {
        return mongoTemplate.findOne(Query.query(Criteria.where("cookie_id").is(cookidId)), SessionData.class);
    }

    public SessionData isLoginIn(Long single) {
        SessionData data = mongoTemplate.findOne(Query.query(Criteria.where("userId").is(single)),SessionData.class);
        return data;
    }

    public void saveOrUpdate(SessionData data) {
        List<SessionData> sessionData = mongoTemplate.find(Query.query(Criteria.where("userId").is(data.getUserId())),SessionData.class);
        if(!ToolsImpl.isEmpty(sessionData)){
            mongoTemplate.findAllAndRemove(Query.query(Criteria.where("userId").is(data.getUserId())),SessionData.class);
        }
        mongoTemplate.save(data);
    }

    public SessionData getByUserId(Long userId) {
        return mongoTemplate.findOne(Query.query(Criteria.where("user_id").is(userId)),SessionData.class);
    }

    public SessionData isAppLogIn(String jsessionid) {
        SessionData data = mongoTemplate.findOne(Query.query(Criteria.where("session_id").is(jsessionid)),SessionData.class);
        return data;
    }
}
